package com.yupi.springbootinit.job.once;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.esdao.PostEsDao;
import com.yupi.springbootinit.model.dto.post.PostEsDTO;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全量同步帖子到 es
 *
 * @author gek
 * @from gek
 */
// todo 取消注释开启任务
//@Component
@Slf4j
public class FullSyncPostToMysql implements CommandLineRunner {

    @Resource
    private PostService postService;


    @Override
    public void run(String... args) {
        String json = "{\"current\":1,\"pageSize\":8,\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"category\":\"文章\",\"tags\":[],\"reviewStatus\":1}";
        String url = "https://api.code-nav.cn/api/post/search/page/vo";
        String result2 = HttpRequest.post(url)
                .body(json)
                .execute().body();
        Map map = JSONUtil.toBean(result2, Map.class);
        JSONObject jsonData = (JSONObject) map.get("data");
        JSONArray records = (JSONArray) jsonData.get("records");
        ArrayList<Post> posts = new ArrayList<>();
        for (Object temprecord : records) {
            JSONObject record= (JSONObject) temprecord;
            Post post = new Post();
            Long id = Long.valueOf(record.getStr("id"));
            post.setId(id);
            if(!StrUtil.hasBlank(record.getStr("title"))){
                post.setTitle(record.getStr("title"));
            }
            if(!StrUtil.hasBlank(record.getStr("content"))){
                post.setContent(record.getStr("content"));
            }
            JSONArray tags = (JSONArray) record.get("tags");
            List<String> tagsList = tags.toList(String.class);
            if(!StrUtil.hasBlank(JSONUtil.toJsonStr(tagsList))){
                post.setTags(JSONUtil.toJsonStr(tagsList));
            }
            post.setUserId(1784095511584137218L);
            post.setCreateTime(new Date());
            post.setUpdateTime(new Date());
            posts.add(post);
        }
        boolean b = postService.saveBatch(posts);
        if(b){
            log.info("postService:存储文章成功");
        }else{
            log.info("postService:存储文章失败");
        }
    }
}
